<?php
/**
 * 抽奖结果记录
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/7
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Coupon;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class CouponCard
 * @package App\Models\Coupon
 *
 * @property CouponTicket coupon_ticket
 * @property Carbon started_at
 * @property Carbon ended_at
 * @property int wechat_user_id
 * @property int is_used
 *
 * @mixin Builder
 * @mixin \Illuminate\Database\Query\Builder
 */
class CouponCard extends Model
{
    protected $table = 'coupon_cards';
    protected static $unguarded = true;

    const NOT_USED = 0;
    const IS_USED = 1;

    protected $casts = [
        'wechat_user_id' => 'int',
        'is_used'        => 'int',
    ];

    protected $dates = ['started_at', 'ended_at'];

    /**
     * @used-by $coupon_ticket
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function couponTicket()
    {
        return $this->belongsTo(CouponTicket::class);
    }

    /**
     * @return int
     */
    public function updateUse(): int
    {
        return $this->update([
            'is_used' => self::IS_USED
        ]);
    }

    public function isDateAvailable(): bool
    {
        $now = now();

        return ($this->started_at <= $now)
            && ($now <= $this->ended_at);

    }
}